<template>
  <div v-loading="loading" element-loading-text="文件上传中......">
    <!--查询表单-->
    <div class="search-div">
      <el-form label-width="70px" size="small">
        <el-row>
          <el-col :span="24">
            <el-form-item label="关键字">
              <el-input
                style="width: 100%"
                v-model="searchObj.keyword"
                placeholder="输入关键字"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="display: flex">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="fetchPageList()">搜索
          </el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetData">重置</el-button>
        </el-row>
      </el-form>
    </div>

    <!-- 工具条 -->
    <div class="tools-div">
      <el-button type="success" icon="el-icon-plus" size="mini" @click="add">添 加</el-button>
    </div>

    <!--增加或修改-->
    <el-dialog title="添加/修改" :visible.sync="dialogVisible" width="40%">
      <el-form
        ref="dataForm"
        :model="sysPet"
        label-width="150px"
        size="small"
        style="padding-right: 40px"
      >
        <el-form-item label="宠物名称">
          <el-input v-model="sysPet.name" placeholder="请输入宠物名称"/>
        </el-form-item>

        <el-form-item label="年龄">
          <el-input v-model="sysPet.age" type="number" placeholder="请输入宠物年龄"/>
        </el-form-item>


        <el-form-item label="主人名称" prop="userId">
          <el-select v-model="sysPet.userId" placeholder="请选择主人名称">
            <el-option
              v-for="item in this.userList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="宠物性别">
          <el-select v-model="sysPet.sex" placeholder="请选择宠物性别">
            <el-option label="公" value="公"></el-option>
            <el-option label="母" value="母"></el-option>
            <el-option label="绝育公" value="绝育公"></el-option>
            <el-option label="绝育母" value="绝育母"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="宠物种类" prop="petTypeId">
          <el-select v-model="sysPet.type" placeholder="请选择宠物种类">
            <el-option
              v-for="item in this.typeList"
              :key="item.id"
              :label="item.type"
              :value="item.type"
            ></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="宠物种类" prop="petTypeId">
          <el-select v-model="sysPet.variety" placeholder="请选择宠物品种">
            <el-option
              v-for="item in filteredPetVarietyList"
              :key="item.id"
              :label="item.variety"
              :value="item.variety"
            ></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="疫苗接种">
          <el-select v-model="sysPet.vaccine" placeholder="请选择宠物疫苗接种情况">
            <el-option label="按时接种" value="0"></el-option>
            <el-option label="没有按时接种" value="1"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="驱虫情况">
          <el-select v-model="sysPet.deworming" placeholder="请选择宠物性别">
            <el-option label="没有驱虫" value="没有驱虫"></el-option>
            <el-option label="体内" value="体内"></el-option>
            <el-option label="体外" value="体外"></el-option>
            <el-option label="内外同驱" value="内外同驱"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="体重">
          <el-input v-model="sysPet.weight" type="number" placeholder="请输入宠物体重"/>
        </el-form-item>


        <el-form-item label="宠物图片" prop="imageUrl">
          <el-upload
            class="upload-demo"
            name="uploadImage"
            action="http://localhost:8085/lovePet/system/upload/uploadImage"
            :limit="1"
            :on-success="handleImageSuccess"
            :before-upload="handleBeforeUpload"
            :show-file-list="false"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>


      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button
          @click="dialogVisible = false"
          size="small"
          icon="el-icon-refresh-right">取 消</el-button>
        <el-button
          type="primary"
          icon="el-icon-check"
          @click="saveOrUpdate()"
          size="small">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      stripe
      border
      style="width: 100%; margin-top: 10px"
    >
      <el-table-column label="序号" width="70" align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>


      <el-table-column prop="name" label="宠物名称"/>
      <el-table-column prop="userId" label="主人名称" :formatter="userFormatter"/>
      <el-table-column prop="sex" label="性别"/>
      <el-table-column prop="age" label="年龄"/>
      <el-table-column prop="type" label="种类"/>
      <el-table-column prop="variety" label="品种"/>

      <!-- el-table 组件的其他代码 -->
      <el-table-column label="疫苗接种">
        <template slot-scope="scope">
          {{ getVaccineStatus(scope.row.vaccine) }}
        </template>
      </el-table-column>

      <el-table-column prop="deworming" label="驱虫情况"/>
      <el-table-column prop="weight" label="体重"/>


      <!--<el-table-column prop="director" label="导演" width="160" />-->

      <!--<el-table-column prop="imageUrl" label="图片">-->
      <!--  <template slot-scope="scope">-->
      <!--    {{scope.row.imageURL}}-->
      <!--    <viewer>-->
      <!--      <img :src="scope.row.imageURL" alt="" style="height: 80px" />-->
      <!--    </viewer>-->
      <!--  </template>-->
      <!--</el-table-column>-->

      <el-table-column prop="imageUrl" label="图片">
        <template slot-scope="scope">
          <viewer>
            <img :src="scope.row.imageUrl" alt="" style="height: 80px"/>
          </viewer>
        </template>
      </el-table-column>


      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="edit(scope.row.id)"
            title="修改"
          />
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeDataById(scope.row.id)"
            title="删除"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      style="padding: 30px 0; text-align: center"
      layout="total, prev, pager, next, jumper"
      @current-change="fetchPageList"
    />


  </div>
</template>

<script>
  // 导入
  import api from "@/api/sysPet/sysPet.js";

  // 导入健康状态
  import healthapi from "@/api/sysPetHealth/sysPetHealth.js";

  // 导入用户
  import userapi from "@/api/user/user.js";

  // 导入宠物类别
  import typeapi from "@/api/sysPetType/sysPetType.js";

  // 导入宠物品种
  import varietyapi from "@/api/sysPetVariety/sysPetVariety.js";


  export default {
    data() {
      return {
        list: [],
        page: 1,
        limit: 5,
        tota: 0,
        searchObj: {},
        listLoading: false,
        dialogVisible: false,
        sysPet: {},
        fileurl: "",
        loading: false,
        VideodialogVisible: false,
        fileList: [],

        //列表
        healthList: [],
        userList: [],
        typeList: [],
        varietyList: [],

      };
    },

    created() {
      //this.listLoading=true;
      this.fetchPageList();
      this.findAll();
    },


    computed: {
      filteredPetVarietyList() {

        if (this.sysPet.type === '' || this.sysPet.type === null) {
          return []; // 如果没有选定typeId，则返回空数组
        } else {
          // 根据选定的typeId过滤varietyList

          let typeId = '';
          for (let i = 0; i < this.typeList.length; i++) {
            if (this.typeList[i].type === this.sysPet.type){
              typeId = this.typeList[i].id;
              break;
            }
          }

          return this.varietyList.filter((item) => item.typeId === typeId);
        }
      },
    },

    methods: {

      getVaccineStatus(vaccine) {
        return vaccine === '0' ? '按时接种' : '没有按时接种';
      },

      //根据id获取用户
      userFormatter(row) {
        let id = row.userId;
        let name = '';
        for (let i = 0; i < this.userList.length; i++) {
          if (this.userList[i].id === id) {
            name = this.userList[i].name;
            break;
          }
        }
        return name;
      },

      //根据id获取健康状态
      healthStatusFormatter(row) {
        let id = row.healthStatusId;
        let name = '';
        for (let i = 0; i < this.healthList.length; i++) {
          if (this.healthList[i].id === id) {
            name = this.healthList[i].healthStatus;
            break;
          }
        }
        return name;
      },

      //根据id获取宠物类别
      petTypeFormatter(row) {
        let id = row.petTypeId;
        let name = '';
        for (let i = 0; i < this.typeList.length; i++) {
          if (this.typeList[i].id === id) {
            name = this.typeList[i].type;
            break;
          }
        }
        return name;
      },


      showPlayPage(row) {
        this.$router.push('/system/assignVideo?id=' + row.id);
      },

      //发现宠物健康状态、用户、宠物类别列表
      findAll() {
        healthapi.findAll().then((response) => {
          this.healthList = response.data;
        });
        userapi.findAll().then((response) => {
          this.userList = response.data;
        });
        typeapi.findAll().then((response) => {
          this.typeList = response.data;
        });
        varietyapi.findAll().then((response) => {
          this.varietyList = response.data;
        });
      },

      add() {
        this.sysPet = {};
        this.dialogVisible = true;
      },

      edit(id) {
        //1.弹框
        this.dialogVisible = true;
        //2.赋值
        api.getSysPetById(id).then((response) => {
          this.sysPet = response.data;
        });
      },

      //文件开始上传,开始屏幕遮罩
      handleBeforeUpload() {
        this.loading = true;
      },

      //图片上传成功的钩子函数
      handleImageSuccess(res, file) {

        console.log(res);  // 得到的是图片地址
        console.log(file);  // 得到是一个对象

        this.loading = false;
        if (file.response != "") {
          // this.sysMovie.image = file.response.data;
          this.sysPet.imageUrl = file.response;
          this.fileList = [];
          console.log("=================" + this.sysPet.imageUrl);
          this.$message({
            type: "info",
            message: "图片上传成功",
            duration: 6000,
          });

        } else {
          this.fileList = [];
          this.$message({
            type: "info",
            message: "图片上传失败",
            duration: 6000,
          });
        }
      },

      handleVideoSuccess(res, file) {
        this.loading = false;
        if (file.response != "") {

          console.log(res);  // 得到的是
          console.log(file);  // 得到是

          this.sysPet.playId = file.response.data;

          console.log("========================" + this.sysPet.playId)

          this.$message({
            type: "info",
            message: "视频上传成功",
            duration: 6000,
          });
        } else {
          this.$message({
            type: "info",
            message: "视频上传失败",
            duration: 6000,
          });
        }
      },

      saveOrUpdate() {
        if (this.sysPet.id != null) {
          this.updatePet();
        } else {
          this.addPet();
        }
      },

      addPet() {
        api.savePet(this.sysPet).then((response) => {
          this.$message({
            type: "success",
            message: "添加成功!",
          });
          //关闭弹框
          this.dialogVisible = false;
          // 刷新列表
          this.fetchPageList();
        });
      },

      updatePet() {
        api.updatePet(this.sysPet).then((response) => {
          this.$message({
            type: "success",
            message: "修改成功!",
          });
          //关闭弹框
          this.dialogVisible = false;
          // 刷新列表
        });
        this.fetchPageList();
      },


      removeDataById(id) {
        this.$confirm("此操作将永久删除该影视, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          api.removePetById(id).then((response) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.fetchPageList();
          });
        });
      },

      //重置
      resetData() {
        //1.清空搜索条件
        this.searchObj = {};
        //2.再次刷新列表
        this.fetchPageList();
      },

      //获取数据
      fetchPageList(page = 1) {
        this.page = page;
        api.getPageList(this.page, this.limit, this.searchObj)
          .then((response) => {
            this.list = response.data.records;
            this.total = response.data.total;
          });
      },
    },
  };
</script>

<style lang="less" scoped>
</style>
